/**
 * Created by SImon on 2018/1/11.
 */
import wepy from 'wepy'
import CryptoJS from 'crypto-js'


// var baseurl = "http://192.168.0.188:36666/"  // 测试环境
// var baseurl = "http://192.168.0.166:36666/"  // 测试环境

//var baseurl = "https://s113.dev.idingding.com/"  // 体验环境

var baseurl = "https://v.idingding.com/"  // 正式环境

// var root = baseurl + "gateway.do";  // 测试环境
var root = baseurl + "gateway";  // 测试环境
var appid = "f60cbc2ae4d74262a248a4df0e9012cc";  //  应用id
var aes_key = "1D622919A070SDM1";  //  AES密钥
//WXAppID= wx3f8c9ee76754347e

var login_status = false

//用户登录
function Login(testthis){
  // wepy.setStorageSync("cc_user_id", '3');
  // wepy.setStorageSync("cc_user_token", 'abc');
  // return
  if (login_status) {
    return
  }
  login_status = true
  const that = this
  //获取code
  wepy.login({
    success:function(res) {
      //console.log(res.code)
      //请求自己服务器登陆
      //code	String	用户允许登录后，回调内容会带上 code（有效期五分钟），
      // 开发者需要将 code 发送到开发者服务器后台，使用code 换取 session_key api，
      // 将 code 换成 openid 和 session_key

      //console.log(res.code)
      var params = {};
      params.code =res.code
      var launchOptions = wx.getLaunchOptionsSync()
      params.scene_value = launchOptions.scene

      if (launchOptions.query) {
        if (launchOptions.query.s) {
          params.src = launchOptions.query.s
          params.src_value = launchOptions.query.v
        } else if (launchOptions.query.scene) {

          var scene = decodeURIComponent(launchOptions.query.scene)

          var scene1 = scene.split(',')
          for (var i = 0; i < scene1.length; i++) {
            var scene2 = scene1[i].split(':')
            scene2[0] = '\"' + scene2[0] + '\"'
            scene2[1] = '\"' + scene2[1] + '\"'
            scene1[i] = scene2.join(':')
          }
          var scene3 = '{' + scene1.join(',') + '}'
          var scene4 = JSON.parse(scene3)
          params.src = scene4.s
          params.src_value = scene4.v

          // var str = decodeURIComponent(launchOptions.query.scene)
          // var src = str.split('+')[1].split(':')
          // params.src = src[1]
          // var src_value = str.split('+')[2].split(':')
          // params.src_value = src_value[1]
        } else {
          params.src = 0
          params.src_value = 0
        }

      } else {
        params.src = 0
        params.src_value = 0
      }

      _api_base('POST','cc_global_register_login',params,
          function success(res){
            // console.log(res)
            wepy.setStorageSync("cc_user_id", res.data.user_id);
            wepy.setStorageSync("cc_user_token", res.data.user_token);

            setTimeout(function () {
              var currentPages = getCurrentPages()
              if (currentPages.length > 0) {
                var currentPage = currentPages[currentPages.length-1]
                currentPage.onShow()
              }
            },500)

            setTimeout(function () {
              login_status = false
            },3000)

            // console.log('wepy.login')

          }, function fail(res){
            //console.log(res)
          login_status = false
          },that)

    },
    fail:function () {
      login_status = false
    }

  })
}

/*
 接口处理函数
 */
function _api_base(method,url, params, success, failure, testthis) {

  var httpparams;
  if (params) {
    if (wx.getStorageSync('cc_user_id')) {
      params.user_id = wx.getStorageSync('cc_user_id')
      params.user_token = wx.getStorageSync('cc_user_token')
    }
    //params = filter_null(params);
    var parmstr = JSON.stringify(params);
    var key = CryptoJS.enc.Utf8.parse(aes_key);
    var srcs = CryptoJS.enc.Utf8.parse(parmstr);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    var encryptedstr = encrypted.ciphertext.toString().toUpperCase();

    httpparams = {
      'appid':appid,
      'method':url,
      'sign':encryptedstr
    };

  } else {
    httpparams = {
      "appid":appid,
      "method":url
    };
  }
  wx.request({
    url: root,
    data: httpparams,
    method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'Content-Type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
    },
    success: function (res) {
      // console.log(res)
      res = res.data
      if (res.code == 1) {
        success(_decrypt(res.sign));
        //console.log(_decrypt(res.sign))
      } else if (res.code == 2) {
        console.log("参数不能为空");
      } else if (res.code == 3) {
        console.log("接口方法名有误");
      } else if (res.code == 4) {
        console.log("appid有误");
      } else if (res.code == 5) {
        console.log("请求密文有误");
      } else if (res.code == 6) {
        console.log("用户id与用户token不能为空");
        Login()
      } else if (res.code == 7) {
        console.log("用户token不存在或已失效");
        Login()
      }
    },
    fail: function (res) {
      console.log(res)
    },
    complete: function () {
    }
  })
}
function _decrypt(word) {
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var key = CryptoJS.enc.Utf8.parse(aes_key);
  var decrypt = CryptoJS.AES.decrypt(srcs, key, { mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return JSON.parse(decryptedStr.toString());
}
// GET请求
function GET (method,url, params, success, failure, testthis) {
  _api_base(method,url, params, success, failure, testthis)
}
// POST请求
function POST (method,url, params, success, failure, testthis) {
  _api_base(method,url, params, success, failure, testthis)
}

module.exports = {
  get: GET,
  post: POST,
  login:Login,
}

